<?php declare(strict_types=1);

namespace Core\Repository\Admin;

use Core\Repository\BaseRepository;
use Core\Service\UserService;
use Core\Service\RolesService;
/**
 * PassportRepository
 * 通行证仓库
 * @package Core\Repositories\Admin
 *
 * @property UserService $userService
 * @property RolesService $rolesService
 */
 class UserRepository extends BaseRepository
 {
     /**
      * getUserList
      * 获取列表
      * @param $inputData
      * @return array
      */
     public function getUserList($inputData)
     {
         $pagesInfo = $this->userService->getPagesInfo($inputData);
         $where = $inputData;
         unset($where['limit']);
         unset($where['page']);
         $count = $this->userService->getCount($where);
         $order = ['created_at'=>'DESC'];
         $list = $this->userService->getList($where,$order,$pagesInfo['offset'],$pagesInfo['limit']);

         return [
             'total' => $count,
             'data' => $list
         ];
     }

     /**
      * saveUser
      * 保存
      * @param $data
      * @return null
      * @throws \Exception
      */
     public function saveUser($data)
     {
         $saveRoles = [];
         $tmp = [];
         if (isset($data['user_roles'])) {
             $tmp = $data['user_roles'];
             unset($data['user_roles']);
         }
         // 判断是否是创建还是修改
         $type = true;
         if (isset($data['id']) && $data['id']) {
             $type = false;
         }
         $userId = $this->userService->saveUser($data,$type);
         $time = date('Y-m-d H:i:s',time());
         foreach ($tmp as $v) {
             $saveRoles[] = [
                 'system_role_id' => $v,
                 'user_id' => $userId,
                 'created_at' => $time,
                 'updated_at' => $time,
             ];
         }
         $this->rolesService->deleteRolesUser(['user_id' => $userId]);
         $this->rolesService->saveUserRoles($saveRoles);
         return $userId;
     }

     /**
      * getInfo
      * 根据id获取信息
      * @param $id
      * @return \App\Model\Model|\Hyperf\Database\Model\Model|null
      */
     public function getInfo($id)
     {
         $info = $this->userService->getInfo($id);
         $info['user_roles'] = $this->rolesService->getUserRoles($id);
         return $info;
     }

     /**
      * deleteInfo
      * 删除信息
      * @param $id
      * @return mixed
      */
     public function deleteInfo($id)
     {
         $info = $this->userService->deleteInfo($id);
         $where = ['user_id' => $id];
         $this->rolesService->deleteRolesUser($where);
         return $info;
     }

     /**
      * getRolesList
      * 获取权限信息
      * @return mixed
      */
     public function getRolesList()
     {
         return $this->rolesService->getList();
     }
 }